// pages/ruKuDaYin/ruKuDaYin.js
const footer = require('../footer/footer.js');
const consoleIMG = require('./consoleIMG.js');
import JCAPI from "../../utils/JCAPI/JCAPI";
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    ruKu2WeiZhiXing: [],
    isSelect: '2',
    modalHidden: true,
    imgurl: [],
    consoleTab: true,
    count4danhao: 0,
    Plist: [],
    printTab: false,
    nowPrint: [],
    RuKulHidden: true,
    danhao: "",
    remark: "",
    QRCodeListIndex: 0,
    QRCodeList: [],
  },
  pageReSetClick: function (params) {
    footer.pageReSetClick(params)
  },
  /**
   * 点击取消
   */
  modalCandel: function (params) {
    // do something
    this.setData({
      modalHidden: true
    })
  },

  /**
    *  点击确认
    */
  modalConfirm: function () {
    // do something
    this.setData({
      modalHidden: true
    })
  },
  RuKuCandel: function (params) {
    // do something
    this.setData({
      RuKulHidden: true
    })
  },

  /**
    *  点击确认
    */
  RuKuConfirm: function (params) {
    // do something
    this.setData({
      RuKulHidden: true
    })
    var that = this
    //this.danhaoSet(this.data.danhao,app.globalData.userId,this.data.count4danhao)
    var dataget = wx.request({
      url: 'https://127.0.0.1:10270/api/rukuWancheng?danhao=' + that.data.danhao
        + "&remark=" + that.data.remark,
      method: "post",
      success: (result) => {
        console.log(result);
        wx.showModal({
          title: '操作执行结果',
          content: result.data == 1 ? '入库成功' : '入库失败',
        })
        dataget.abort()
      },
    })
    wx.redirectTo({
      url: '/pages/ruKuDaYin/ruKuDaYin',
    })
  },
  ruKuSaoMa: function (params) {
    var imgid = params.currentTarget.dataset.id
    this.data.ruKu2WeiZhiXing.forEach(element => {
      if (element["id"] == imgid) {
        getApp().globalData.logShangpin = element["shangpin"]
      }
    })
    wx.navigateTo({
      url: '/pages/console/console',
    })
  },
  ruKuZhiXing: function (params) {
    var danhao = params.currentTarget.dataset.id
    var remark = params.currentTarget.dataset.remark
    this.setData({
      RuKulHidden: false,
      danhao: danhao,
      remark: remark
    })
  },
  tiaoMaYuLan: function (params) {
    var imgid = params.currentTarget.dataset.id
    this.data.ruKu2WeiZhiXing.forEach(element => {
      if (element["id"] == imgid) {
        this.setData({
          imgurl: element["shangpin"],
          modalHidden: false
        })
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      nowPrint: app.globalData.nowPrint != null ? app.globalData.nowPrint : []
    })
    var that = this
    var userid = app.globalData.userId
    var dataget = wx.request({
      url: 'https://127.0.0.1:10270/api/Return2WeiXin?userId=' + userid + '&type=2',
      data: {
        userId: that.data.userId
      },
      method: "post",
      success: (result) => {
        that.setData({
          ruKu2WeiZhiXing: result.data.gouhuorukuReturnList
        })
        console.log(that.data.ruKu2WeiZhiXing);
        dataget.abort()
      },
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onSaveExitState: function () {
    JCAPI.closePrinter()
    consoleIMG.bluetoothEnd()
  },
  ruKuQuanDanDaYin: function (params) {
    var that = this
    console.log(params.currentTarget.dataset.id);
    var id = params.currentTarget.dataset.id
    var weiruku = []
    this.data.ruKu2WeiZhiXing.forEach((item) => {
      if (item.id == id) {
        weiruku = item
        console.log(weiruku);
      }
    })
    var imglist = []
    weiruku.shangpin.forEach((item) => {
      if (item.shangpinleibie != '闭门器' && item.shangpinleibie != '拉爆盖') {
        var list = { "imgurl": item.shangpintiaoma, "count": item.shangpinshuliang }
      imglist.push(list)
      }
    })
    wx.showModal({
      title: '整单打印确认',
      content: '请仔细核对是否需要打印本单所有商品',
      complete: (res) => {
        if (res.cancel) {
          //取消
          //  console.log("cancel")
        }
        if (res.confirm) {
          //确认
          // console.log("confirm")
          consoleIMG.linkPrint().then((result) => {
            console.log("linkPrint start")
            console.log(result);
            that.setData({
              Plist: result,
              printTab: true,
              QRCodeList: imglist
            })
          }
          )
        }
      }
    })
  },
  printTabCandel: function () {
    // do something
    this.setData({
      printTab: false
    })
  },
  /**
    *  点击确认
    */
  printTabConfirm: function () {
    // do something
    var print2p = this.data.nowPrint != null ? this.data.nowPrint : this.data.Plist[0];
    if (print2p != null) {
      this.setData({
        printTab: false,
        nowPrint: print2p
      })
      wx.showLoading({  // 显示加载中loading效果 
        title: "打印中......",
        mask: true  //开启蒙版遮罩
      });
      this.QRCodeLog()
    } else {
      wx.showToast({
        title: '请选择打印机',
        icon: 'error'
      })
    }
  },

  QRCodeLog: function () {
    var that = this
    console.log(that.data.QRCodeList);
    consoleIMG.consoleIMGList(that.data.QRCodeList, that.data.nowPrint)
        .then(result => {
          console.log(result);
          wx.hideLoading();
          wx.showToast({
            title: "打印完成",
            icon: "success",
          })
          getApp().globalData.printingCount = 0
          that.setData({
            QRCodeList:[],
            QRCodeListIndex:0
          })
        });
    },
    openPrinter(e){
      console.log("openPrinter start");
      let item = {}
      if (wx.getStorageSync('print')){
        item = wx.getStorageSync('print')
      }
      if (e&&e.currentTarget.dataset.item){
        item = e.currentTarget.dataset.item
      }
      let self = this;
      // let name = "S6-D726050099"
      wx.showLoading({
        title: '连接中',
        mask: true
      });
      JCAPI.openPrinter(item.name,function(){
        wx.showToast({
          title: '连接打印机成功',
          icon: '',
          image: '',
          duration: 2000,
          mask: true,
          success: function (res) {
            wx.hideLoading();
            let Printer = self.data.Plist;
            var arr = Printer.filter(function (items) {
              return items.name !== item.name;
            });
            wx.setStorageSync('print', item)
            getApp().globalData.nowPrint = item
            self.setData({
              nowPrint: item,
              Plist: arr
            })
          },
        })
      setTimeout(()=>
     {
       console.log("hello World");
     }, 2000)
      },function(){
        self.setData({
          nowPrint: ""
        })
        wx.removeStorageSync("print")
        wx.showToast({
          title: '连接失败',
          icon: 'error',
          duration: 2000
        })
      });
    },
    disconnect: function(e) {
      console.log("disconnect start");
      let self = this
      // wx.hideLoading()
      wx.showToast({
        title: '打印机连接断开',
        icon: '',
        image: '',
        duration: 2000,
        mask: true,
        success: function (res) {
          self.setData({
            nowPrint: ""
          })
          wx.removeStorageSync("print")
          // self.scanedPrinters()
        },
        fail: function (res) { },
        complete: function (res) { },
      })
      JCAPI.closePrinter();
    },
})